<template>
  <div class="list-content">
    <div class="list-content-center">
      <div class="list-item" v-for="(item, i) in list" :key="i">
        <div class="list-item-content-img">
          <img :src="item.url" alt="" />
        </div>
        <div class="list-item-content-text">
          <div class="list-item-content-text-title">{{ item.title }}</div>
          <div class="list-item-content-text-desc">{{ item.discription }}</div>
        </div>
      </div>
      <div class="list-component-loading">
        <ASpin size="small" tip="Loading..."></ASpin>
      </div>
    </div>
  </div>
</template>
<script setup>
const props = defineProps({
  config: {
    type: Object,
    default: {
      type: 1, // 1卡片
      pageSize: 10,
      isScrollBottonLoad: true,
    },
  },
  data: {
    type: Array,
    default: () => [],
  },
});

let emit = defineEmits();

/**
 * 可视范围监听
 */
let observer = null;
/**
 * 观察目标元素
 */
let target = null;

/**
 * 滚动容器
 */
let dom = null;

/**
 * 滚动位置记录
 */
let top = 0;

/**
 * 当前页码
 */

let page = 1;

/**
 * 数据列表
 */
const list = ref([]);

watch(
  () => props.data,
  (val) => {
    list.value = val;
  },
  {
    immediate: true,
    deep: true,
  }
);

/**
 * 可视范围监听回调
 */

const comm = props.config;
const ObserverCallback = (entries, observer) => {
  // entries 是一个数组，里面存放着所有可见元素
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      console.log("进入可视区域", dom.scrollTop);
      if (dom.scrollTop > top) {
        page++;
        top = dom.scrollTop + 25;
        emit("List_Onload", comm, page);
        console.log(top, "toptoptop");
      }
    } else {
      console.log("离开可视区域", dom.scrollTop);
    }
  });
};

onMounted(() => {
  /**
   * 滚动容器
   */
  dom = document.querySelector(".list-content");
  /**
   * 可视范围监听
   */
  observer = new IntersectionObserver(ObserverCallback, {
    root: dom, // 默认为视窗
    rootMargin: "0px", // 视窗的外边距
    threshold: 0.5, // 目标元素可见比例达到 10% 时触发回调
  });

  /**
   * 观察目标元素
   */

  target = document.querySelector(".list-component-loading");
  observer.observe(target);
});
</script>
<style lang="scss" scoped>
.list-content {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  position: absolute;
}
.list-content-center {
  max-width: 1200px;
  margin: 0 auto;
}
.list-item {
  display: flex;
  border-bottom: 1px solid var(--colorBorder);
  padding: 10px 0;
  .list-item-content-img {
    width: 18.75%;
    margin-right: 10px;
    img {
      width: 100%;
    }
  }
  .list-item-content-text {
    flex: 1;
    .list-item-content-text-title {
      font-size: 16px;
      margin-bottom: 10px;
    }
  }
}
.list-component-loading {
  text-align: center;
  height: 50px;
  line-height: 50px;
}
</style>
